<template>
  <div class="publish">
    <!-- 1.0 面包屑组件 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{
        this.id ? "文章编辑" : "发布文章"
      }}</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片组件 -->
    <el-card class="box-card">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="form.title"></el-input>
        </el-form-item>
        <el-form-item label="栏目" prop="categories">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group v-model.trim="form.categories">
            <el-checkbox
              v-for="item in cateList"
              :key="item.id"
              :label="item.id"
              name="categories"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">文章</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容">
          <VueEditor
            :config="config"
            ref="vueEditor"
            v-show="form.type === 1"
          />
          <!-- 上传视频 -->
          <el-upload
            v-show="form.type === 2"
            class="upload-demo"
            :action="$baseURL + '/upload'"
            :headers="headers"
            :before-upload="VideoBeforeUpload"
            :on-success="videoSuccess"
            :on-remove="onRemoveVdeo"
            :file-list="videoList"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传视频</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传MP4文件，且不超过1MB
            </div>
          </el-upload>
        </el-form-item>
        <!-- 上传图片 -->
        <el-form-item label="封面">
          <el-upload
            :action="$baseURL + '/upload'"
            list-type="picture-card"
            :headers="headers"
            :on-success="onSuccess"
            :on-remove="onRemove"
            :limit="3"
            :on-exceed="onExceed"
            :file-list="form.cover"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{
            this.id ? "编辑文章" : "提交"
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";
import { getToken } from "@/utils/localData";
import {
  PostEssayAPI,
  getPosDetatAPI,
  getCategoryAPI,
  PostBjianEssayAPI,
} from "@/apis/user";
export default {
  components: {
    VueEditor,
  },
  data() {
    return {
      id: this.$route.params.id,
      form: {
        // 栏目数据
        categories: [], // 栏目id
        title: "",
        type: 1,
        content: "", //文章内容
        cover: [], //封面
      },
      rules: {
        title: [
          { required: true, message: "请输入栏目名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        // 栏目
        categories: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个栏目",
            trigger: "change",
          },
        ],
      },
      headers: { Authorization: getToken() },
      cateList: [],
      checkAll: false,
      isIndeterminate: false,
      config: {
        // 上传图片的配置
        uploadImage: {
          // url，name，headers 都要按接口文档的来
          url: this.$baseURL + "/upload",
          name: "file",
          // 🔔 由于这里并不是 axios 发送的请求，所以需要独立配置一下请求头
          headers: { Authorization: getToken() },
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          // 💥 因为内部要用到 this，所以要改成箭头函数写法
          uploadSuccess: (res, insert) => {
            console.log(res);
            if (res.data.message === "文件上传成功") {
              // 用于把图片插入到富文本编辑器中的(图片完整路径)
              insert(this.$baseURL + res.data.data.url);
            } else {
              this.$message.warning("文件上传有误");
            }
          },
        },
      },
      // 用于展示的视频列表
      videoList: [],
    };
  },
  async created() {
    // console.log(this.$baseURL);
    // 获取栏目数据
    const res = await getCategoryAPI();
    console.log(res);
    this.cateList = res.data.data.slice(2);
    // 如果路由参数中有di，就是编辑文章，需要先获取到原来的文章详情
    if (this.id) {
      // 获取文章详情数据
      const res2 = await getPosDetatAPI(this.id);
      console.log(res2);
      const articleObj = res2.data.data;
      if (articleObj) {
        // 获取文章数据，显示到页面中，
        this.form.title = articleObj.title;
        // 选中的栏目
        this.form.categories = articleObj.categories.map((item) => item.id);
        // 类型
        this.form.type = articleObj.type;
        // 文章内容
        this.form.content = articleObj.content;
        if (this.form.type === 1) {
          const quill = this.$refs.vueEditor.editor;
          quill.clipboard.dangerouslyPasteHTML(0, articleObj.content);
        } else {
          // console.log('设置视频')
          this.videoList = [{ name: "mp4视频", url: articleObj.content }];
        }
        // 5.封面
        this.form.cover = articleObj.cover.map((item) => {
          // 通过map处理成【name：id】
          return { id: item.id, name: item.id, url: this.$baseURL + item.url };
        });
      } else {
        this.$message.error("文章不存在");
      }
    }
  },
  methods: {
    onRemoveVdeo() {
      // 把视频数据清空一下
      this.form.content = "";
    },
    // 上传视频
    VideoBeforeUpload(file) {
      console.log("当前文件对象是", file);
      if (file.type !== "video/mp4" || file.size >= 1 * 1024 * 1024) {
        this.$message.warning("上传的文件不是 MP4 格式，或者超过文件最大限制");
        return false;
      }
    },
    // 视频上传成功的回调
    videoSuccess(res) {
      if (res.message === "文件上传成功") {
        this.form.content = this.$baseURL + res.data.url;
      } else {
        this.$message.warning("上传失败失败");
      }
    },
    // 文件超出个数限制时的钩子
    onExceed() {
      this.$message.warning("图片文件上传不能超过3张");
    },
    // 文件上传成功时的钩子
    onSuccess(res) {
      // 封面数组也要按接口文档要求来
      if (res.message === "文件上传成功") {
        this.form.cover.push({
          // 这里需要拼接才能看到完整的封面路径
          id: res.data.id,
          name: res.data.id,
          url: this.$baseURL + res.dangerouslyPasteHTML.url,
        });
      } else {
        this.$message.warning("上传出问题了");
      }
    },
    // 文件列表移除文件时的钩子
    // file: 当前被移除的
    onRemove(file) {
      const id = file.response ? file.response.data.id : file.id;
      this.form.cover = this.form.cover.filter((itme) => itme.id !== id);
    },
    async onSubmit() {
      if (/^.{3,20}$/.test(this.form.title.trim()) === false) {
        return this.$message.warning("标题不能少于3个字符");
      }
      if (this.form.categories.length === 0) {
        this.$message.warning("至少选择一个栏目");
      }
      if (this.form.cover.length === 0) {
        this.$message.warning("至少选择一个封面");
      }
      if (this.form.type == 1) {
        // 按照后端字段要求，保存到 content 字段中，为发布文章做准备
        this.form.content = this.$refs.vueEditor.editor.root.innerHTML;
        if (this.form.content === "<p><br></p>") {
          return this.$message.warning("新闻内容不能空");
        }
      } else if (this.form.type === 2 && this.form.content === "") {
        return this.$message.warning("请上传视频");
      }
      const data = {
        ...this.form,
        cover: this.form.categories.map((item) => {
          return { id: item.id };
        }),
        categories: this.form.categories.map((item) => {
          return { id: item };
        }),
      };
      // console.log(data);
      if (this.id) {
        const res = await PostBjianEssayAPI(this.id, data);
        console.log(res);
        if (res.data.message === "文章编辑成功") {
          this.$message.success("文章编辑成功");
          this.$router.push("/home/post_list");
        }
      } else {
        const res = await PostEssayAPI(data);
        console.log(res);
        // 发布成功后的提示和页面跳转
        if (res.data.message === "文章发布成功") {
          const firs = this.form.type === 1 ? "文章发布成功" : "视频发布成功";
          this.$message.warning(firs);
          this.$router.push("/home/post_list");
        }
      }
    },
    // 全选操作
    handleCheckAllChange(val) {
      // 栏目数据的值是否为全选，否则如果不是为假，为假的时候数组为空
      this.form.categories =
        val === true ? this.cateList.map((item) => item.id) : [];
      this.isIndeterminate = false;
    },
  },
  watch: {
    // 监听categories里面的某一个数据（vlaue）
    "form.categories"(value) {
      console.log("栏目数据发生了变换", value);
      let checkedCount = this.form.categories.length;
      // 说明全选状态和单选的原数组是否一致，
      this.checkAll = checkedCount === this.cateList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cateList.length;
    },
  },
};
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 15px;
}
</style>
